using System;
using System.Threading;

using TrueCode.Core.Diagnostics;

namespace TrueCode.Core.Threading
{
	public class ReaderLock : IDisposable
	{
		#region Fields
		private				bool				_disposed;
		private readonly	ReaderWriterLock	_readerWriterLock;
		#endregion

		#region .ctors
		private ReaderLock( ReaderWriterLock readerWriterLock ) : this( readerWriterLock, -1 )
		{
		}

		private ReaderLock( ReaderWriterLock readerWriterLock, int millisecondsTimeout )
		{
			#region Validation
			if(! DebugAssert.IsNotNull( readerWriterLock, "readerWriterLock" ) )
			{
				throw new Exception<ReaderLock, ArgumentNullException>( new ArgumentNullException("readerWriterLock"));
			}
			#endregion

			_readerWriterLock = readerWriterLock;
			_readerWriterLock.AcquireReaderLock( millisecondsTimeout );
		}
		#endregion

		#region IDisposable Members
		public void Dispose( )
		{
			if( ! _disposed )
			{
				_disposed = true;
				_readerWriterLock.ReleaseReaderLock( );
			}
		}
		#endregion

		public static IDisposable Lock(ReaderWriterLock access)
		{
			#region Validation
			ExceptionHelper.ThrowIfArgumentIsNull< ReaderLock >(access, "access");
			#endregion
			return new ReaderLock(access);
		}
	}
}
